package com.df.monitor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class TaskMonitor {
    
    private final AtomicLong totalProcessingTime = new AtomicLong(0);
    private final AtomicInteger totalTasksProcessed = new AtomicInteger(0);
    private final AtomicInteger totalTasksReceived = new AtomicInteger(0);
    private final AtomicLong lastTaskTime = new AtomicLong(0);
    
    /**
     * 记录任务接收
     */
    public void recordTaskReceived() {
        totalTasksReceived.incrementAndGet();
        lastTaskTime.set(System.currentTimeMillis());
    }
    
    /**
     * 记录任务处理完成
     */
    public void recordTaskCompleted(long processingTime) {
        totalTasksProcessed.incrementAndGet();
        totalProcessingTime.addAndGet(processingTime);
    }
    
    /**
     * 每30秒输出性能统计
     */
    @Scheduled(fixedRate = 30000)
    public void logPerformanceStats() {
        int received = totalTasksReceived.get();
        int processed = totalTasksProcessed.get();
        long totalTime = totalProcessingTime.get();
        long lastTask = lastTaskTime.get();
        
        if (processed > 0) {
            double avgProcessingTime = (double) totalTime / processed;
            long timeSinceLastTask = System.currentTimeMillis() - lastTask;
            
            log.info("=== 任务性能统计 ===");
            log.info("总接收任务数: {}", received);
            log.info("总处理任务数: {}", processed);
            log.info("平均处理时间: {:.2f}ms", avgProcessingTime);
            log.info("距离上次任务: {}ms", timeSinceLastTask);
            log.info("处理率: {:.2f}%", (double) processed / received * 100);
            log.info("==================");
        }
    }
} 